package com.hzjh.base.ext.utils

import android.annotation.SuppressLint
import android.content.Context
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
import com.hzjh.base.ext.widget.textview.MyImageSpan

object TextUtils {
    @SuppressLint("UseCompatLoadingForDrawables")
    fun addTextIcon(context:Context, textView:TextView, imgResource:Int,clickImgResource:((widget: View)->Unit)?=null) {
        //在原始字符串中插入一个空格，插入的位置为numberPerLine - 1
        val stringBuilder =  StringBuilder("${textView.text} ")

        //SpannableString的构建
        val spannableString = SpannableString("$stringBuilder ")
        val drawable = context.resources.getDrawable(imgResource,null)
        drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
        val imageSpan =  MyImageSpan(drawable)
        spannableString.setSpan(imageSpan, spannableString.length - 1, spannableString.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        clickImgResource?.let {
            textView.movementMethod = LinkMovementMethod.getInstance()
            //去掉高亮，不然点击时候背景会变高亮
            textView.highlightColor = context.resources.getColor(android.R.color.transparent,null)
            spannableString.setSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    it.invoke(widget)
                }
            }, spannableString.length - 1, spannableString.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        }
        textView.text = spannableString
    }
}